package com.mfy.controller;

import com.mfy.entity.vo.MsgVO;
import com.mfy.util.SMSUtils;
import com.mfy.utils.RedisPrefix;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class SMSController {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private SMSUtils smsUtils;
    @PostMapping("/captchas")
    public void sendMsg(@RequestBody MsgVO msgVO){
        String varify = RandomStringUtils.randomNumeric(4);
        log.info("手机验证码: "+varify);
        //一个手机号码有三次发短信的机会
        Integer count = (Integer) redisTemplate.opsForValue().get(RedisPrefix.PHONE_COUNT_KEY + msgVO.getPhone());
        if (count == null || count<3){
            //2.把手机号和验证码放入到redis中
            redisTemplate.opsForValue().set(RedisPrefix.PHONE_KEY+msgVO.getPhone(),varify,60, TimeUnit.SECONDS);
            redisTemplate.opsForValue().increment(RedisPrefix.PHONE_COUNT_KEY + msgVO.getPhone());

            if (count == null){
                redisTemplate.expire(RedisPrefix.PHONE_COUNT_KEY + msgVO.getPhone(),24,TimeUnit.HOURS);
            }
        }else {
            throw new RuntimeException("手机发送验证码超过三次,你没事吧!!!,明天再来!-.-");
        }
    }
}
